package com.thinkgem.jeesite.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.enums.SqlLike;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.common.utils.SessionUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.SysAreaMapper;
import com.thinkgem.jeesite.modules.sys.entity.SysArea;
import com.thinkgem.jeesite.modules.sys.utils.SysCacheUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 20:45 2018/8/13
 * @Modified By:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysAreaService extends ServiceImpl<SysAreaMapper, SysArea> implements IService<SysArea> {
    public SysArea get(String id) {
        // 先从缓存获取
        SysArea sysArea = SysCacheUtils.getSysArea(id);
        if (null != sysArea) {
            return sysArea;
        }

        // 缓存中不存在，则从数据库获取
        sysArea = this.baseMapper.selectById(id);
        if (null != sysArea) {
            SysCacheUtils.putSysArea(sysArea.getId(), sysArea);
        }
        return sysArea;
    }

    public List<SysArea> getAllOrdered() {
        QueryWrapper queryWrapper = new QueryWrapper<SysArea>();
        queryWrapper.orderByAsc(SysArea.COL_CODE);
        return this.list(queryWrapper);
    }

    /**
     *
     * @param id
     * @return
     */
    public List<SysArea> selectChildren(String id) {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<SysArea>();
        }

        QueryWrapper queryWrapper = new QueryWrapper<SysArea>();
        String param = "";
        if (BaseConstants.ROOT_AREA_ID.equals(id)) {
            param = id + ",";
            queryWrapper.likeLeft(SysArea.COL_PARENT_IDS, param);
        } else {
            param = "," + id + ",";
            queryWrapper.like(SysArea.COL_PARENT_IDS, param);
        }
        queryWrapper.orderByAsc(SysArea.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询直接子机构
     *
     * @param id
     * @return
     */
    public List<SysArea> selectDirectChildren(String id) {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<SysArea>();
        }

        QueryWrapper queryWrapper = new QueryWrapper<SysArea>();
        queryWrapper.eq(SysArea.COL_PARENT_ID, id);
        queryWrapper.orderByAsc(SysArea.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Transactional( rollbackFor = Exception.class)
    public boolean saveArea(SysArea sysArea) {
        if (StringUtils.isBlank(sysArea.getId())) {
            return this.insertArea(sysArea);
        }
        return this.updateArea(sysArea);
    }

    @Transactional( rollbackFor = Exception.class)

    public boolean insertArea(SysArea sysArea) {
        // 设置parentids的值
        SysArea parentArea = this.baseMapper.selectById(sysArea.getParentId());
        sysArea.setParentIds(parentArea.getParentIds() + sysArea.getParentId() + ",");

        // 设置sort值
        if (null == sysArea.getSort()) {
            sysArea.setSort(30);
        }

        // 保存
        this.baseMapper.insert(sysArea);
        return true;
    }

    @Transactional( rollbackFor = Exception.class)
    public boolean updateArea(SysArea sysArea) {
        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = sysArea.getParentIds();

        // 设置新的父节点串
        SysArea parentArea = this.baseMapper.selectById(sysArea.getParentId());
        sysArea.setParentIds(parentArea.getParentIds() + sysArea.getParentId() + ",");

        // 设置sort值
        if (null == sysArea.getSort()) {
            sysArea.setSort(30);
        }

        // 保存或更新实体
        this.baseMapper.updateById(sysArea);

        // 更新子节点 parentIds
        List<SysArea> subAreaList = this.selectChildren(sysArea.getId());
        for (SysArea subArea : subAreaList) {
            subArea.setParentIds(subArea.getParentIds().replace(oldParentIds, sysArea.getParentIds()));
            this.baseMapper.updateById(subArea);
        }
        // 清除用户菜单缓存
        SessionUtils.removeAttrArea();
        // 清除日志相关缓存
        SysCacheUtils.removeSysAreaAll();
        return true;
    }

    @Transactional( rollbackFor = Exception.class)
    public void delete(SysArea sysArea) {
        this.removeById(sysArea.getId());
        // TODO：删除与区域的关系
        SessionUtils.removeAttrArea();
    }

}
